package com.montran.timer.task;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;

public class ScheduleTask {

	// PRIVATE
	private final ScheduledExecutorService fScheduler;
	private final long fInitialDelay;
	private final long fDelayBetweenRuns;
	private final long fShutdownAfter;

	/** If invocations might overlap, you can specify more than a single thread. */
	private static final int NUM_THREADS = 1;
	private static final boolean DONT_INTERRUPT_IF_RUNNING = false;
	
	//private List<Runnable> listTask
	
	ScheduleTask(long aInitialDelay, long aDelayBetweenBeeps, long aStopAfter) {
		fInitialDelay = aInitialDelay;
		fDelayBetweenRuns = aDelayBetweenBeeps;
		fShutdownAfter = aStopAfter;
		fScheduler = Executors.newScheduledThreadPool(NUM_THREADS);
	}

	/** Sound the alarm for a few seconds, then stop. */
	void activateScheduleTask() {
		Runnable soundAlarmTask = new FutureTask();
		ScheduledFuture<?> soundAlarmFuture = fScheduler
				.scheduleWithFixedDelay(soundAlarmTask, fInitialDelay,
						fDelayBetweenRuns, TimeUnit.SECONDS);
		Runnable stopAlarm = new StopTask(soundAlarmFuture);
		fScheduler.schedule(stopAlarm, fShutdownAfter, TimeUnit.SECONDS);
	}

	 class StopTask implements Runnable{
		  private ScheduledFuture<?> fSchedFuture;
			StopTask(ScheduledFuture<?> aSchedFuture){
			      fSchedFuture = aSchedFuture;
			    }
			    public void run() {
			      
			      fSchedFuture.cancel(DONT_INTERRUPT_IF_RUNNING);
			      /* 
			       Note that this Task also performs cleanup, by asking the 
			       scheduler to shutdown gracefully. 
			      */
			      fScheduler.shutdown();
			    }
			  
	}
			  


}
